﻿
/*
 * ************************************************************************
 *                            SDK
 *                      网络SDK(C#版)示例程序
 * 
 * 版 本 号:0.01
 * 文件名称:frm_PlayBackByFileSet.cs
 * 功能说明:按文件回放检索画面
 * 作    者:李德明
 * 作成日期:2007/11/26
 * 修改日志:    日期        版本号      作者        变更事由
 *              2007/11/26  0.01        李德明      新建作成
 * 
 * ************************************************************************
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DHNetSDK;
using System.Runtime.InteropServices;
using Utility;
//
using DHNetSDK;
using Utility;
using System.Runtime.InteropServices;
using DLLTest.OpertionClass;

namespace DLLTest
{
    public partial class frm_PlayBackByFileSet : Form
    {
        /// <summary>
        /// 使用扩展分屏类
        /// </summary>
        private PanelOpertionExt panelopertionExt = new PanelOpertionExt();

        /// <summary>
        /// 程序消息提示Title
        /// </summary>
        private const string pMsgTitle = "网络文件下载程序";
        /// <summary>
        /// 最后操作信息显示格式
        /// </summary>
        private const string pErrInfoFormatStyle = "代码:errcode;\n描述:errmSG.";
        /// <summary>
        /// 用户登录ID
        /// </summary>
        public int gLoginID;

        /// <summary>
        /// 选择的文件信息
        /// </summary>
        public NET_RECORDFILE_INFO gFileInfo;

        /// <summary>
        /// 文件信息查询结果
        /// </summary>
        private NET_RECORDFILE_INFO[] nriFileInfo;

        /// <summary>
        /// 最多查询文件数
        /// </summary>
        private const int intFilesMaxCount = 1024;

        /// <summary>
        /// 确认按钮是否按下
        /// </summary>
        public bool blnOKEnter = false;

        /// <summary>
        /// 提示消息标题
        /// </summary>
        private const string strMsgTitle = "网络视频文件下载程序";
        /// <summary>
        /// 用户信息
        /// </summary>
        private USER_MANAGE_INFO userManageInfo;
        /// <summary>
        /// 常规报警信息
        /// </summary>
        private NET_CLIENT_STATE clientState;

        private double dblDownLoadPos;

        private delegate void fSetProgressPos(int lPlayHandle, UInt32 dwTotalSize, UInt32 dwDownLoadSize);

        private fSetProgressPos setProgressPos;

        //private string strUserName = "";

        private NET_DEVICEINFO deviceInfo;//网络设备信息

        #region 文件下载
        /// <summary>
        /// 按文件下载句柄
        /// </summary>
        private int pDownloadHandleByFile;
        /// <summary>
        /// 按时间下载句柄
        /// </summary>
        private int pDownloadHandleByTime;
        /// <summary>
        /// 下载句柄
        /// </summary>
        private int pDownloadHandle;
        /// <summary>
        /// 断开回调
        /// </summary>
        private fDisConnect disConnect;
        /// <summary>
        /// 下载回调
        /// </summary>
        private fDownLoadPosCallBack downLoadFun;

        //private fTimeDownLoadPosCallBack timeDownLoadFun;
        /// <summary>
        /// 下载进度百分比
        /// </summary>
        #endregion

        #region 回放定义
        /// <summary>
        /// 回放句柄保存
        /// </summary>
        private int[] pPlayBackHandle;

        /// <summary>
        /// 回放通道号
        /// </summary>
        private int pPlayBackChannelID;

        /// <summary>
        /// 播放方式
        /// </summary>
        private int playBy = 0;

        /// <summary>
        /// 当前回放的文件信息
        /// </summary>
        NET_RECORDFILE_INFO fileInfo;

        #endregion

        public frm_PlayBackByFileSet()
        {
            InitializeComponent();

            pPlayBackHandle = new int[intFilesMaxCount];
            PanelOpertionExt.SelectedPanel = panel1;
        }

        private void frm_PlayBackByFileSet_Load(object sender, EventArgs e)
        {
            //通道选择列表,默认通道号
            //默认选择项
            cmbChannelSelect.SelectedIndex = 0;
            //txtChannelID.Text = cmbChannelSelect.SelectedIndex.ToString();
            //记录文件类型默认选择
            cmbRecordFileTypeSelect.SelectedIndex = 0;
            //btnOK按钮没有被按下
            blnOKEnter = false;
            btnOK.Enabled = false;
            //设置播放和下载按钮不能使用
            btnFileDownload.Enabled = false;
            btnCancel.Enabled = false;
            btnPlayByRecordFile.Enabled = false;
            gpbPlayBackControl.Enabled = false;
            //开始日期为当前日期的前一周
            dtpStart.Value = DateTime.Now.AddDays(-7);
            ////开始日期为当前日期的前一月
            //dtpStart.Value = DateTime.Now.AddMonths(-1);

            StringUtil.InitControlText(this);
            if (PanelOpertion.SelectedPanel != null && 
                PanelOpertion.SelectedPanel.Tag != null)
            {
                #region 提取通道号,取出正在播放的通道号
                string[] panUD = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
                txtDevName.Text = panUD[0].ToString();//保存文件名,以ip地址开头                 
                gLoginID = Convert.ToInt32(panUD[4].ToString());//登录pLogin                
                txtChannelID.Text = panUD[5].ToString();//通道号 
                //cmbChannelSelect.SelectedIndex = Convert.ToInt32(txtChannelID.Text);
                #endregion
            }
            else
            {
                MessageUtil.ShowMsgBox(StringUtil.ConvertString("请选择正在播放的通道后在选择下载!"),
                    StringUtil.ConvertString(pMsgTitle));
                this.Close();
            }
        }

        /// <summary>
        /// 查询按钮单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, EventArgs e)
        {
            #region << 画面操作 >>
            int channelID = 0;
            RECORD_FILE_TYPE rfType = RECORD_FILE_TYPE.ALLRECORDFILE;
            if (txtChannelID.Text.Trim().Length == 0)
            {
                MessageUtil.ShowMsgBox(StringUtil.ConvertString("请输入通道号!"),
                                       StringUtil.ConvertString(strMsgTitle));
                return;
            }
            else
            {
                channelID = int.Parse(txtChannelID.Text);
            }
            if (txtDevName.Text.Trim().Length == 0)
            {
                MessageUtil.ShowMsgBox(StringUtil.ConvertString("请输入设备名!"),
                                       StringUtil.ConvertString(strMsgTitle));
                return;
            }
            if (cmbRecordFileTypeSelect.SelectedIndex == -1)
            {
                MessageUtil.ShowMsgBox(StringUtil.ConvertString("请选择文件类型!"),
                                       StringUtil.ConvertString(strMsgTitle));
                return;
            }
            else
            {
                switch (cmbRecordFileTypeSelect.SelectedIndex)
                {
                    case 0:
                        rfType = RECORD_FILE_TYPE.ALLRECORDFILE;
                        break;
                    case 1:
                        rfType = RECORD_FILE_TYPE.OUTALARM;
                        break;
                    case 2:
                        rfType = RECORD_FILE_TYPE.DYNAMICSCANALARM;
                        break;
                    case 3:
                        rfType = RECORD_FILE_TYPE.ALLALARM;
                        break;
                    case 4:
                        rfType = RECORD_FILE_TYPE.CARDNOSEACH;
                        break;
                    case 5:
                        rfType = RECORD_FILE_TYPE.COMBINEDSEACH;
                        break;

                }
            }

            string strTmStart = dtpStart.Text + " " + txtTimeStart.Text;
            string strTmEnd = dtpEnd.Text + " " + txtTimeEnd.Text;

            DateTime tmStart;
            DateTime tmEnd;

            try
            {
                tmStart = DateTime.Parse(strTmStart);
                tmEnd = DateTime.Parse(strTmEnd);
            }
            catch (System.Exception ex)
            {
                MessageUtil.ShowMsgBox(StringUtil.ConvertString("请输入正确的时间格式!"),
                                       StringUtil.ConvertString(strMsgTitle));
                return;
            }

            if (tmStart >= tmEnd)
            {
                MessageUtil.ShowMsgBox(StringUtil.ConvertString("开始日期不在结束日期前!"),
                                       StringUtil.ConvertString(strMsgTitle));
                return;
            }

            #endregion

            #region << 查询操作 >>

            nriFileInfo = new NET_RECORDFILE_INFO[intFilesMaxCount];
            string strTimeFormatStyle = "yyyy年mm月dd日 hh:MM:ss";//日期时间格式化字符，具体定义请参见NET_TIME结构的ToSting方法说明
            int intFileCount = 0;
            bool blnQueryRecordFile = false;
            blnQueryRecordFile = DHClient.DHQueryRecordFile(gLoginID, channelID, rfType, tmStart, tmEnd, null, ref nriFileInfo, intFilesMaxCount * Marshal.SizeOf(typeof(NET_RECORDFILE_INFO)), out intFileCount, 5000, false);
            if (blnQueryRecordFile == true)
            {
                lsvFiles.Items.Clear();
                if (0 == intFileCount)
                {
                    MessageUtil.ShowMsgBox(StringUtil.ConvertString("未查询到录像文件!"),
                                           StringUtil.ConvertString(strMsgTitle));
                    return;
                }

                ListViewItem lvi;
                for (int i = 0; i < intFileCount; i++)
                {
                    lvi = new ListViewItem();
                    lvi.SubItems[0].Text = txtDevName.Text + nriFileInfo[i].ch.ToString();
                    lvi.SubItems.Add(nriFileInfo[i].starttime.ToString(strTimeFormatStyle));
                    lvi.SubItems.Add(nriFileInfo[i].endtime.ToString(strTimeFormatStyle));
                    lvi.SubItems.Add(nriFileInfo[i].size.ToString());
                    lsvFiles.Items.Add(lvi);
                }
                return;
            }
            else
            {
                btnFileDownload.Enabled = false;
            }
            return;
            #endregion
        }

        /// <summary>
        /// 文件下载确认按钮单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFileDownload_Click(object sender, EventArgs e)
        {
            if (PanelOpertion.SelectedPanel == null)
            {
                return;
            }
            if (blnOKEnter == true)//如果文件选项成立
            {
                fileInfo = gFileInfo;
                string strtemp = Application.StartupPath + @".\DHFiles\DH_";
                string strFileName = txtDevName.Text + "_" + txtChannelID.Text;
                strFileName = strFileName.ToLower();
                if (!strFileName.EndsWith(".dav"))
                    strFileName += ".dav";
                //if (!strFileName.EndsWith(".avi"))//不能使用，文件很大，估计是大华做了设置
                //    strFileName += ".avi";
                //strtemp += strFileName;          
                //**********按文件下载**********
                if (strtemp.Length > 2)//如果路径及文件名不为空
                {
                    pDownloadHandleByFile = DHClient.DHDownloadByRecordFile(gLoginID, fileInfo, strtemp + strFileName, downLoadFun, IntPtr.Zero);
                    if (pDownloadHandleByFile != 0)
                    {
                        btnFileDownload.Text = "下载中";
                        pDownloadHandle = pDownloadHandleByFile;
                        btnFileDownload.Enabled = false;
                        //**********画面控制代码**********
                        btnCancel.Enabled = true;
                        btnPlayByRecordFile.Enabled = false;
                        gpbPlayBackControl.Enabled = false;
                        //**************
                        // MessageUtil.ShowMsgBox(StringUtil.ConvertString("开始下载!"),StringUtil.ConvertString(pMsgTitle));
                        MessageBox.Show("开始下载！");
                    }
                    else
                    {
                        MessageUtil.ShowMsgBox(StringUtil.ConvertString(DHClient.LastOperationInfo.errMessage, "ErrorMessage"),
                                                StringUtil.ConvertString(pMsgTitle));
                    }
                }
                //****************               
            }
        }

        /// <summary>
        /// 取消按钮单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (btnFileDownload.Text.Equals("下载中"))
            {
                bool blnStopSucced = DHClient.DHStopDownload(pDownloadHandleByFile);
                if (blnStopSucced)
                {
                    blnOKEnter = false;
                    btnCancel.Enabled = false;
                    //MessageUtil.ShowMsgBox(StringUtil.ConvertString("停止下载成功！"), StringUtil.ConvertString(pMsgTitle));
                    MessageBox.Show("停止下载成功！");
                }
                else
                {
                    MessageUtil.ShowMsgBox(StringUtil.ConvertString(DHClient.LastOperationInfo.errMessage, "ErrorMessage"),
                                           StringUtil.ConvertString(pMsgTitle));
                }
                //btnFileDownload.Tag = "";              
            }
            else
            {
                //MessageUtil.ShowMsgBox(StringUtil.ConvertString("当前没有下载任务!"),
                //                       StringUtil.ConvertString(pMsgTitle));
            }
        }

        private void btnPlay4_Click(object sender, EventArgs e)
        {
            btnPlay4.Enabled = false;
            btnPlay1.Enabled = !btnPlay4.Enabled;

            panelopertionExt.SplitScreen(4, panel1);
        }

        private void btnPlay1_Click(object sender, EventArgs e)
        {
            btnPlay1.Enabled = false;
            btnPlay4.Enabled = !btnPlay1.Enabled;

            panelopertionExt.SplitScreen(1, panel1);
        }

        private void btnRewind_Click(object sender, EventArgs e)
        {
            DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.Slow);//慢放控制
        }

        private void btnFastForward_Click(object sender, EventArgs e)
        {
            DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.Fast);//快放控制
        }

        private void lsvFiles_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            try
            {
                if (e.ItemIndex != -1)
                {
                    btnOK.Enabled = true;
                    gFileInfo = nriFileInfo[e.ItemIndex];
                }
                else
                {
                    btnOK.Enabled = false;
                }
            }
            catch (System.Exception ex)
            {
            	
            }
        }


        private void btnOK_Click(object sender, EventArgs e)
        {
            if (lsvFiles.SelectedItems == null ||
                  lsvFiles.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择一个播放文件");
                return;
            }
            if (btnFileDownload.Text == "下载中" || gpbPlayBackControl.Enabled == true)
            {
                MessageBox.Show("请先停止下载或播放");
                return;
            }
            blnOKEnter = true;
            //其它按钮的状态
            btnFileDownload.Enabled = true;
            btnPlayByRecordFile.Enabled = true;
            btnPlayByRecordFile.Enabled = true;
            gpbPlayBackControl.Enabled = false;
            //选中的文件赋于信息
            gFileInfo = nriFileInfo[lsvFiles.SelectedItems[0].Index];
        }

        private void btnPlayByRecordFile_Click(object sender, EventArgs e)
        {
            try
            {
                playBy = 0;//播放模式

                //pLoginID，channel已经在formload中获取了
                if (blnOKEnter == true)
                {
                    PanelOpertionExt.SelectedPanel.Refresh();//刷新panle
                    pPlayBackChannelID = int.Parse(txtChannelID.Text.ToString());//获取通道号
                    fileInfo = gFileInfo;//获取文件信息
                    //**********按文件回放**********
                }
                pPlayBackHandle[pPlayBackChannelID] = DHClient.DHPlayBackByRecordFile(gLoginID, ref fileInfo, PanelOpertionExt.SelectedPanel.Handle, null, IntPtr.Zero);
                ////******************************
                if (pPlayBackHandle[pPlayBackChannelID] == 0)
                {
                    MessageBox.Show("按时间回放失败！", pMsgTitle);
                }
                else
                {
                    //**********画面控制代码**********
                    btnPlay.Text = "||";
                    //画面按钮的有效性控制
                    gpbPlayBackControl.Enabled = true;
                    btnPlay.Enabled = true;
                    btnStop.Enabled = true;
                    btnFast.Enabled = true;
                    btnSlow.Enabled = true;
                    hsbPlayBack.Enabled = true;
                    //文件下载为假
                    btnFileDownload.Enabled = false;
                    btnCancel.Enabled = false;


                    btnPlayByRecordFile.Enabled = false;
                }
            }
            catch (System.Exception ex)
            {
            	
            }
            
        }

        private void btnSlow_Click(object sender, EventArgs e)
        {
            DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.Slow);//慢放控制
        }

        private void btnFast_Click(object sender, EventArgs e)
        {
            DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.Fast);//快放控制
        }

        /// <summary>
        /// 播放控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPlay_Click(object sender, EventArgs e)
        {
            switch (btnPlay.Text.ToString())
            {
                case ">"://播放控制
                    if (DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.Play) == true)//播放
                    {
                        btnPlay.Text = "||";
                    }
                    break;
                case "||"://暂停控制
                    if (DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.Pause) == true)//暂停
                    {
                        btnPlay.Text = ">";
                    }
                    break;
            }
        }

        /// <summary>
        /// 通道选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbChannelSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtChannelID.Text = cmbChannelSelect.SelectedIndex.ToString();
        }

        /// <summary>
        /// 拖放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hsbPlayBack_ValueChanged(object sender, EventArgs e)
        {
            ////停止步进播放
            //if (btnStepPlayE.Enabled == true)
            //{
            //    btnStepPlayE_Click(null, null);
            //}

            #region << 拖拽功能 >>

            switch (playBy)//播放方式0:按文件播放;1:按时间播放
            {
                case 0://按文件播放:按字节偏移播放回放
                    DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.SeekByBit, (uint)(hsbPlayBack.Value * (fileInfo.size / 100)));
                    break;
                case 1://按时间播放:按时间编移播放回放
                    DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.SeekByTime,
                                                (uint)(hsbPlayBack.Value * ((fileInfo.endtime.ToDateTime().TimeOfDay.TotalSeconds - fileInfo.starttime.ToDateTime().TimeOfDay.TotalSeconds) / 100)));
                    break;
            }

            #endregion
        }

        /// <summary>
        /// 停止播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (DHClient.DHPlayBackControl(pPlayBackHandle[pPlayBackChannelID], PLAY_CONTROL.Stop) == false)//停止回放
            {
                MessageBox.Show("停止回放失败！", pMsgTitle);
            }
            else
            {
                if (panel1 != null)
                {
                    panel1.Refresh();
                    panel1.BackColor = SystemColors.Control;
                    //********画面控制*******
                    blnOKEnter = false;
                    btnPlayByRecordFile.Enabled = false;
                    btnFileDownload.Enabled = false;
                    gpbPlayBackControl.Enabled = false;
                }
                else
                {
                    panel1.Refresh();
                    panel1.BackColor = SystemColors.Control;
                }
            }
        }

        private void frm_PlayBackByFileSet_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnFileDownload.Enabled == true)
            {
                btnCancel_Click(null, null);
            }
            if (gpbPlayBackControl.Enabled == true)
            {
                btnStop_Click(null, null);
            }
        }
    }
}